<script lang="ts" setup>
import type { DataType } from './types';

import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';

import { Page } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { Button, message, Popconfirm, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deletePage_news, getPage_news ,update_sort} from '#/api/portal/promotion';
import Icon from '#/components/Icons';
import { formatImagesList, queryStringToObject } from '#/utils';

defineOptions({
  name: 'PortalAdminPage',
});

const route = useRoute();
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const viewTitle = routeMeta.title.replace('管理', '');
const code = ref('');

const gridOptions: VxeGridProps<DataType> = {
  rowConfig: {
    isCurrent: true,
    isHover: true,
     drag: true,
  },
  columns: [
    { field: 'id', title: $t('page.common.Code'), dragSort: true },
    { field: 'name', title: $t('page.common.Attribute') },
    { field: 'title', title: $t('page.common.Title') },
    { field: 'images', title: $t('page.common.Thumbnail'), cellRender: { name: 'CellImage' } },
    {
      field: 'update_time',
      title: $t('page.common.UpdatedTime'),
    },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: $t('page.common.Action'),
      width: 240,
    },
  ],
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
    layouts: ['PrevPage', 'NextPage'],
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const param = queryStringToObject(route.meta.param as string);
        if (param?.code) {
          formValues.code = param.code;
          code.value = param.code;
        }

        const { data } = await getPage_news({
          page: page.currentPage,
          limit: page.pageSize,
          ...formValues,
        });
        const total = data.list.length;
        
        data.list = formatImagesList(data.list, 'images');
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};
const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['code'],
      },
      fieldName: 'code',
      label: 'code',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: $t('page.common.Please Enter')+` ${viewTitle}`,
      },
      fieldName: 'keyword',
      label: `${viewTitle} `+$t('page.common.Title'),
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
};
const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
  formOptions,
});




const gridEvents: VxeGridListeners<AddDataType> = {
  async rowDragend() {
    const visibleData = GridApi.grid.getTableData().visibleData;
    const result: { [key: string]: number } = {};
    // 使用 forEach 替代 reduce
    visibleData.forEach((item, index) => {
      result[item.id] = index;
    });

  await update_sort({ list_orders: result });
  },
};


const handleDelete = async (row: DataType) => {
  const $table = GridApi.grid;
  if ($table) {
    const { msg } = await deletePage_news(row.id);
    $table.remove(row);
    message.success(msg);
  }
};

// const openDialog = async (row?: DataType) => {
//   const id = row?.id || 0;
// console.log('可用路由:', router.getRoutes());

//   router.push({
//     name: `PortalpromotionDetail`,
//     params: { id },
//   });
// };

import { useVbenModal} from '@vben/common-ui';
import ExtraModal from './detail.vue';

const [Modal, modalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: ExtraModal,
  class: 'w-4/5', // Tailwind 写法，w-4/5 = 80%
  onClosed:function(){
    console.log('111')
    GridApi.reload();
  }
});
const openDialog = async (row?: DataType) => {
  const id = row?.id || 0;

//  router.push({
//       name: 'HomevechileDetail',
//       params: { id }
//     });

    modalApi.setData({
      id: id,
    });
    modalApi.open();

};
</script>

<template>
  <Page auto-content-height><Modal />
    <Grid :grid-events="gridEvents" :table-title="`${viewTitle} `+$t('page.common.List')">
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="openDialog()">
          <span class="anticon">
            <Icon icon="ri:add-line" />
          </span>
          {{$t('page.common.Add')}} {{ viewTitle }}
        </Button>
      </template>

      <template #action="{ row }">
        <Space>
          <Button type="primary" @click="openDialog(row)">
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:file-edit-line" />
              </span>
            </template>
            {{$t('page.common.Edit')}}
          </Button>
          <Popconfirm
            :cancel-text="$t('page.common.No')"
            :ok-text="$t('page.common.Yes')"
            :title="$t('page.common.Confirm Delete')"
            @confirm="handleDelete(row)"
          >
            <Button danger type="primary">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:delete-bin-line" />
                </span>
              </template>
              {{$t('page.common.Delete')}}
            </Button>
          </Popconfirm>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
